package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.QuestionDetailVO;
import com.asktgapp.user.activity.EngineerDetailActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;

import java.util.Date;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/24
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class AskDetialFragment extends BaseFragment {
    //头部
    @InjectView(R.id.iv_head_ask)
    ImageView mQuestionHead;
    @InjectView(R.id.tv_ask_name)
    TextView mAskName;
    @InjectView(R.id.tv_ask_time)
    TextView mAskTime;
    @InjectView(R.id.tv_question)
    TextView mQuestion;
    //答案
    @InjectView(R.id.iv_answer_head)
    ImageView mAnswerHead;//答题人头像
    @InjectView(R.id.tv_answer_name)
    TextView mAnswerName;//答题人名称
    @InjectView(R.id.tv_answer_tag1)
    TextView mAnswerTag1;
    @InjectView(R.id.tv_answer_tag2)
    TextView mAnswerTag2;
    @InjectView(R.id.tv_answer)
    TextView mAnswer;
    //没有答案的时候
    @InjectView(R.id.tv_no_answer)
    TextView mNoAnswer;
    //底部的浏览人数和赞
    @InjectView(R.id.tv_read_number)
    TextView mReadNumber;
    @InjectView(R.id.tv_zan)
    TextView mLike;
    private String mQuestionId;
    @InjectView(R.id.ll_has_answer)
    LinearLayout mHasAnswerUI;
    @InjectView(R.id.ll_has_answer_display)
    LinearLayout mDisplay;

    @InjectView(R.id.item)
    LinearLayout mSkipToDetail;
    private QuestionDetailVO mQuestionDetailVO;
    private int zan = 0;
    private int number = 0;


    private void setUI(final QuestionDetailVO bean) {
        if(!isVisible())
            return;
        zan = bean.getIs_like();
        number = bean.getLikeNumber();
        ImageDisplayUtil.loadCircleHeadImage(getActivity(), mQuestionHead, bean.getQUserPic());
        mAskName.setText(bean.getQUersName());
        Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
        mAskTime.setText(Util.DateToStr(date, "yyyy-MM-dd"));
        mQuestion.setText(bean.getQContent());
        if (bean.getIsAnswer() == 1) {//已解答
            mHasAnswerUI.setVisibility(View.VISIBLE);
            mNoAnswer.setVisibility(View.GONE);
            mDisplay.setVisibility(View.VISIBLE);

            ImageDisplayUtil.loadCircleHeadImage(getActivity(), mAnswerHead, bean.getAUserPic());
            mAnswerName.setText(bean.getaRealName());
            mReadNumber.setText(String.valueOf(bean.getViewNumber()));
            mLike.setText(String.valueOf(bean.getLikeNumber()));
            mSkipToDetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SkipToEngineerDetail(getActivity(), String.valueOf(bean.getaUserId()));
                }
            });
            if (bean.getIs_like() == 1) {
                mLike.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.zan_1, 0, 0, 0);
            } else {
                mLike.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.zan_2, 0, 0, 0);
            }
            mAnswer.setText("答：" + bean.getAContent());

            String[] des = bean.getALabel().split(",");
            switch (des.length) {
                case 0:
                    mAnswerTag1.setVisibility(View.GONE);
                    mAnswerTag2.setVisibility(View.GONE);
                    break;
                case 1:
                    mAnswerTag1.setText(des[0]);
                    mAnswerTag2.setVisibility(View.GONE);
                    if (Util.isEmpty(des[0])) {
                        mAnswerTag1.setVisibility(View.GONE);
                    } else {
                        mAnswerTag1.setVisibility(View.VISIBLE);

                    }
                    break;
                case 2:
                    mAnswerTag1.setVisibility(View.VISIBLE);
                    mAnswerTag1.setText(des[0]);
                    mAnswerTag2.setVisibility(View.VISIBLE);
                    mAnswerTag2.setText(des[1]);
                    break;
                default:
                    mAnswerTag1.setVisibility(View.VISIBLE);
                    mAnswerTag1.setText(des[0]);
                    mAnswerTag2.setVisibility(View.VISIBLE);
                    mAnswerTag2.setText(des[1]);
                    break;
            }
        } else {
            mHasAnswerUI.setVisibility(View.GONE);
            mNoAnswer.setVisibility(View.VISIBLE);
            mDisplay.setVisibility(View.GONE);
        }


    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_ask_detail, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        mQuestionId = getActivity().getIntent().getStringExtra("id");
        mLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dealZan();
            }
        });

    }

    private void dealZan() {
        if (Util.isEmpty(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
            showTost("未登录，不能点赞！请先登录", 1);
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        if (zan == 0) {
            params.put("temp", 1);
        } else {
            params.put("temp", 0);
        }
        params.put("type", 1);
        params.put("id", mQuestionDetailVO.getAId());
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.doLike(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    if (zan == 0) {
                        zan = 1;
                        mLike.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.zan_1, 0, 0, 0);
                        if (mQuestionDetailVO.getIs_like() == 0) {
                            mLike.setText(String.valueOf(mQuestionDetailVO.getLikeNumber() + 1));
                        } else {
                            mLike.setText(String.valueOf(mQuestionDetailVO.getLikeNumber()));
                        }
                    } else {
                        zan = 0;
                        mLike.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.zan_2, 0, 0, 0);
                        if (mQuestionDetailVO.getIs_like() == 1) {
                            mLike.setText(String.valueOf(mQuestionDetailVO.getLikeNumber() - 1));
                        } else {
                            mLike.setText(String.valueOf(mQuestionDetailVO.getLikeNumber()));
                        }
                    }
                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException exception = ExceptionHandle.handleException(t);
                if (exception.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (exception.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(exception.getMessage(), 1);
                }
            }
        });

    }

    @Override
    public void loadData() {
        visibleLoading();
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("id", mQuestionId);
        if (!Util.isEmpty(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
            params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        }
        Call<ApiResponseBody<QuestionDetailVO>> call = apiservice.getQuestionInfo(params);
        call.enqueue(new Callback<ApiResponseBody<QuestionDetailVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<QuestionDetailVO>> call, Response<ApiResponseBody<QuestionDetailVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    mQuestionDetailVO = response.body().getResult();
                    setUI(mQuestionDetailVO);
                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<QuestionDetailVO>> call, Throwable t) {
                inVisibleLoading();
                visibleNoData();
                ApiException exception = ExceptionHandle.handleException(t);
                if (exception.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (exception.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(exception.getMessage(), 1);
                }

            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
